package com.landi.carkey.updata;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.landi.carkey.R;
import com.landi.carkey.util.FileUtil;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/12/30.
 */

public class UpdateService extends Service {
    private String app_name;// 文件名
    private String down_url;// 下载文件地址
    public static String SAVAE_PATH = Environment.getExternalStorageDirectory() + "/BicycleKeyFile";
    public static String KEY_NAME = "Key_App_Name";
    public static String KEY_URL = "Key_Down_Url";

    private static final int TIMEOUT = 10 * 1000;// 超时
    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;

    // 通知
    private NotificationManager notificationManager;
    private Notification notification;
    private RemoteViews contentView;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        app_name = intent.getStringExtra(KEY_NAME);
        down_url = intent.getStringExtra(KEY_URL);

        if (FileUtil.createFile(SAVAE_PATH, app_name)) {
            createNotification();
            // 线程开启
            new DownLoadThread().start();
        } else {
            stopSelf();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void createNotification() {
        notification = new Notification(R.mipmap.ic_launcher, app_name + "正在下载",
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        // 自定义 Notification 的显示
        contentView = new RemoteViews(getPackageName(), R.layout.item_notification);
        contentView.setTextViewText(R.id.notificationTitle, app_name + "正在下载");
        contentView.setTextViewText(R.id.notificationPercent, "0%");
        contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
        notification.contentView = contentView;
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(R.layout.item_notification, notification);
    }

    private class DownLoadThread extends Thread {

        @Override
        public void run() {
            Message message = new Message();
            try {
                long downloadSize = downloadUpdateFile(down_url, FileUtil.updateFile.toString());
                if (downloadSize > 0) {
                    message.what = DOWN_OK;
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                message.what = DOWN_ERROR;
                handler.sendMessage(message);
            }
        }
    }

    public long downloadUpdateFile(String down_url, String file) throws Exception {
        int totalSize; // 文件总大小
        int downloadCount = 0; // 已经下载好的大小
        int updateCount = 0; // 已经上传的文件大小
        int downCount = 1;// 已下载好的百分比

        InputStream inputStream;
        OutputStream outputStream;

        URL url = new URL(down_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        url.openConnection();
        httpURLConnection.setConnectTimeout(TIMEOUT);
        httpURLConnection.setReadTimeout(TIMEOUT);
        // 获取下载文件的总管大小size
        totalSize = httpURLConnection.getContentLength();

        if (httpURLConnection.getResponseCode() == 404) {
            // 这个地方应该加一个下载失败的处理，但是，因为我们在外面加了一个try---catch，已经处理了Exception,所以不用处理
            throw new Exception("fail!");
        }

        inputStream = httpURLConnection.getInputStream();
        outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉

        byte buffer[] = new byte[1024];
        int readsize = 0;

        while ((readsize = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, readsize);
            downloadCount += readsize;
            int num = downloadCount * 100 / totalSize;
            if (num > downCount || totalSize == downloadCount) {
                downCount = downloadCount * 100 / totalSize;
                // 改变通知栏
                contentView.setTextViewText(R.id.notificationPercent, downCount + "%");
                contentView.setProgressBar(R.id.notificationProgress, 100, downCount, false);
                notification.contentView = contentView;
                notificationManager.notify(R.layout.item_notification, notification);
            }
        }
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        inputStream.close();
        outputStream.close();
        return downloadCount;
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_OK:
                    // 改变通知栏
                    contentView.setTextViewText(R.id.notificationTitle, app_name + "下载完成");
                    notification.contentView = contentView;
                    notificationManager.notify(R.layout.item_notification, notification);
                    //安装
                    Uri uri = Uri.fromFile(FileUtil.updateFile);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    UpdateService.this.startActivity(intent);

                    stopSelf();
                    break;
                case DOWN_ERROR:
                    // 改变通知栏
                    FileUtil.delFile(SAVAE_PATH + "/" + app_name);
                    contentView.setTextViewText(R.id.notificationTitle, app_name + "下载失败");
                    notification.contentView = contentView;
                    notificationManager.notify(R.layout.item_notification, notification);
                    stopSelf();
                    break;
                default:
                    break;
            }
        }
    };

}